package com.etoak.common.web;

import com.etoak.common.core.vo.ResultVO;
import com.etoak.common.web.exception.CustomException;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

//全局异常处理器
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler
    public ResultVO<Object> handle(MethodArgumentNotValidException e){
        log.error(e.getMessage(),e);
        List<ObjectError> allErrors = e.getAllErrors();
        String collect = allErrors.stream().map(ObjectError::getDefaultMessage)
                .collect(Collectors.joining(";"));
        return ResultVO.failed(collect);
    }
    @ExceptionHandler
    public ResultVO<Object> handle(ConstraintViolationException e){
        log.error(e.getMessage(),e);
        String collect = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(";"));
        return ResultVO.failed(collect);
    }
    @ExceptionHandler
    public ResultVO<Object> handle(CustomException e){
        log.error(e.getMessage(),e);
        return ResultVO.failed(e.getMessage());
    }

    /**
     * 处理未知异常 返回系统异常
     * 客户端看到系统异常时 去控制台查看错误日志
     * @param e
     * @return
     */
    @ExceptionHandler
    public ResultVO<Object> handle(Exception e){
        log.error(e.getMessage(),e);
        return ResultVO.failed();
    }
}
